package com.example.musicproject_b.DynamicComponent;

import com.alibaba.fastjson.JSON;
import com.example.common.b_pojo.BAdminUser;
import com.example.common.b_pojo.BRole;
import com.example.musicproject_b.config.MyAccessDeniedHandler;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.example.musicproject_b.Controller.AdminLoginController.USERINFO_PREFIX;

@Slf4j
@Component
public class DynamicPermission {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

//    TODO: 动态鉴权的逻辑
    public boolean checkPermisstion(HttpServletRequest request,
                                   Authentication authentication) throws Exception {
        Object principal = authentication.getPrincipal();
        if(principal instanceof BAdminUser){
            BAdminUser bAdminUser = (BAdminUser) principal;
            Long id = bAdminUser.getId();
            String userinfoRoles = stringRedisTemplate.opsForValue().get(USERINFO_PREFIX + id);
            log.info("用户权限信息："+userinfoRoles);
            if (userinfoRoles == null) {
                throw new Exception("用户信息不存在！");
            }
            List<BRole> admininfo = JSON.parseArray(userinfoRoles, BRole.class);
            List<String> allowedUrls=admininfo.stream()
                    .flatMap(role -> role.getMenuslist().stream())
                    .filter(menu -> menu.getIsdelete() == 0) // 过滤已删除的菜单
                    .map(menu -> menu.getComponent())
                    .collect(Collectors.toList());
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            // 当前访问路径
            String requestURI = request.getRequestURI();
            // 提交类型
            String urlMethod = request.getMethod();
            // 判断当前路径中是否在资源鉴权中
            boolean rs = allowedUrls.stream().anyMatch(allowedUrl -> {
                /**
                 * “/”,表示只匹配根目录，不包含子路径，/**才表示包含子路径
                 */
                boolean hashAntPath = antPathMatcher.match(allowedUrl, requestURI);

                // 判断请求方式是否和数据库中匹配（数据库存储：GET,POST,PUT,DELETE）
//                String dbMethod = urlMethod; // 假设菜单权限中没有存储请求方法，这里直接使用请求方法

                // 两者都成立，返回真，否则返回假
                return hashAntPath;

            });
            if (rs){
                return rs;
            }else {
                return rs;
            }
        }else {
            return false;
        }

    }

}
